import axios from 'axios'
import { /* MessageBox, */ Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import NProgress from 'nprogress' // progress bar 进度条组件
import 'nprogress/nprogress.css' // progress bar style 进度条样式

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests 跨域请求时发送 cookie
  timeout: 5000 // request timeout 请求超时
})

// request interceptor 请求拦截器
service.interceptors.request.use(
  config => {
    // 进度条
    NProgress.start()
    setTimeout(() => NProgress.done(), 500)
    // do something before request is sent
    // 请求发送前

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // 让每个请求携带 token
      // ['X-Token'] 是一个自定义头部 key
      // 请根据实际情况修改
      config.headers['X-Token'] = getToken()
    }

    return config
  },
  error => {
    // do something with request error
    // 请求错误时
    Message.error(error)
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor 响应拦截器
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    // 如果自定义代码不是200，就会被判定为错误。
    if (res.code !== 200) {
      Message.error(res.msg || 'Error')

      /* // ? 其他场景
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      // 50008: 非法令牌; 50012: 其他登录的客户机; 50014: 令牌过期;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm(
          '您已经注销，您可以取消留在此页面，或重新登录',
          '确认退出',
          {
            confirmButtonText: '重新登陆',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      */
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      Message.success(res.msg)
      return res.data
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message.error(error.message)
    return Promise.reject(error)
  }
)

// 请求工具封装
const request = (url, data = {}, method = 'get') =>
  service({
    url,
    method,
    [method.toLowerCase() === 'get' ? 'params' : 'data']: data
  })

export default request
